package com.example.demo.repository;

import com.example.demo.model.TextDocument;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface TextDocumentRepository extends JpaRepository<TextDocument, Long> {
    List<TextDocument> findByFeaturedTrue();
    
    // 根据分类ID查询文档
    List<TextDocument> findByCategoryId(Long categoryId);
    
    // 查询今日创建的文档数量
    long countByCreatedAtBetween(LocalDateTime startOfDay, LocalDateTime endOfDay);
    
    // 优化的查询方法
    List<TextDocument> findByIsPublicTrueOrderByCreatedAtDesc();
    
    List<TextDocument> findAllByOrderByCreatedAtDesc();
    
    @Query("SELECT d FROM TextDocument d WHERE d.isPublic = true OR d.author = :author ORDER BY d.createdAt DESC")
    List<TextDocument> findByIsPublicTrueOrAuthorOrderByCreatedAtDesc(@Param("author") String author);
    
    List<TextDocument> findByFeaturedTrueOrderByCreatedAtDesc();
    
    @Query("SELECT d FROM TextDocument d WHERE d.isPublic = true AND d.featured = true ORDER BY d.createdAt DESC")
    List<TextDocument> findByIsPublicTrueAndFeaturedTrueOrderByCreatedAtDesc();
    
    @Query("SELECT d FROM TextDocument d WHERE (d.featured = true AND d.isPublic = true) OR (d.featured = true AND d.author = :author) ORDER BY d.createdAt DESC")
    List<TextDocument> findByFeaturedTrueAndIsPublicTrueOrFeaturedTrueAndAuthorOrderByCreatedAtDesc(@Param("author") String author);
    
    @Query("SELECT d FROM TextDocument d WHERE d.category.id = :categoryId AND d.isPublic = true ORDER BY d.createdAt DESC")
    List<TextDocument> findByCategoryIdAndIsPublicTrueOrderByCreatedAtDesc(@Param("categoryId") Long categoryId);
    
    @Query("SELECT d FROM TextDocument d WHERE d.category.id = :categoryId ORDER BY d.createdAt DESC")
    List<TextDocument> findByCategoryIdOrderByCreatedAtDesc(@Param("categoryId") Long categoryId);
    
    @Query("SELECT d FROM TextDocument d WHERE (d.category.id = :categoryId AND d.isPublic = true) OR (d.category.id = :categoryId AND d.author = :author) ORDER BY d.createdAt DESC")
    List<TextDocument> findByCategoryIdAndIsPublicTrueOrCategoryIdAndAuthorOrderByCreatedAtDesc(@Param("categoryId") Long categoryId, @Param("author") String author);
    
    @Query("SELECT d FROM TextDocument d WHERE d.id = :id AND d.isPublic = true")
    TextDocument findByIdAndIsPublicTrue(@Param("id") Long id);
    
    @Query("SELECT d FROM TextDocument d WHERE d.id = :id AND (d.isPublic = true OR d.author = :author)")
    TextDocument findByIdAndIsPublicTrueOrAuthor(@Param("id") Long id, @Param("author") String author);
} 